﻿using IConfiguration;
using IService;
using Models;
using System;
using EFContext;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace Service {
  public class UserService : ServiceBase, IUserService {
    IUtils _utils;
    public UserService(IEFContext.IEFContext EFContext, IUtils utils) : base(EFContext) {
      _utils = utils;
    }
    public List<RoleInfo> GetRolesByUserId(int userId) {
      var roles = (from ur in Context.Set<UserRole>()
                   where ur.UserId == userId
                   select ur.RoleId).ToList();
      return (from role in Context.Set<RoleInfo>()
              where roles.Contains(role.RoleId)
              select role).ToList();
    }

    public void ResetPassword(int userId) {
      Context.Set<SysUserInfo>().Where(u => u.UserId == userId).ToList()
        .ForEach(u => u.Password = _utils.GetMD5Str(_utils.GetMD5Str("123456") + "|" + u.UserName));
      Context.SaveChanges();
    }

    public void SaveUser(string data) {
      var value = Newtonsoft.Json.JsonConvert.DeserializeObject<SysUserInfo>(data);
      if (value.UserId == 0) {
        value.UserIcon = "images/avatar.jpg";
        value.Password = _utils.GetMD5Str(_utils.GetMD5Str("123456") + "|" + value.UserName);
      }
      Context.Entry(value).State = value.UserId == 0 ? EntityState.Added : EntityState.Modified;
      Context.SaveChanges();
    }
  }
}
